package com.googlecode.olabs.gui.client.resources;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.Window;
import com.googlecode.olabs.gui.client.rest.AbstractRestResource;
import com.googlecode.olabs.gui.client.rest.RestRequestBuilder;

public class Card extends AbstractRestResource {

	private final String m_cardId;
	private String m_cardText;

	public Card(String cardId) {
		m_cardId = cardId;
	}

	public String getCardId() {
		return m_cardId;
	}

	public String getCardText() {
		return m_cardText;
	}

	public String getTitle() {
		if (isLoaded()) {
			return m_cardText;
		}
		return "...";
	}

	public boolean isLoaded() {
		return m_cardText == null || m_cardText.isEmpty();
	}

	public void load() {
		RestRequestBuilder builder = RestRequestBuilder.create(
				RestRequestBuilder.GET, CardCollection.URL + "/" + m_cardId);
		try {
			builder.sendRequest(new RequestCallback() {
				public void onError(Request request, Throwable exception) {
					Window.alert("Error refreshing card: " + exception);
				}

				public void onResponseReceived(Request request,
						Response response) {
					m_cardText = response.getText();
					notifyObservers();
				}
			});
		} catch (RequestException e) {
			Window.alert("Exception sending request: " + e);
		}
	}
}
